package funcs

import (
	"sync"
	"time"
)

//go协程管理器，用于死循环的关闭
type LoopStore struct {
	sync.Mutex
	state  bool
	stoped chan bool
}

//tm=时间(time.Duration 或者 string)
func Loop(tm interface{}, call func()) *LoopStore {
	var t time.Duration
	if ttm, ok := tm.(time.Duration); ok {
		t = ttm
	} else if ttm, ok := tm.(string); ok {
		t, _ = time.ParseDuration(ttm)
	}
	if t <= 0 {
		return nil
	}
	obj := new(LoopStore)
	obj.stoped = make(chan bool)
	obj.state = true
	go func() {
		for {
			if !obj.state {
				obj.stoped <- true
				return
			}
			time.Sleep(t)
			func() {
				obj.Lock()
				defer obj.Unlock()
				call()
			}()
		}
	}()
	return obj
}

//关闭这个死循环
func (this *LoopStore) Stop() {
	this.state = false
	<-this.stoped
}
